module VIM

  class Functions
    def self.method_missing(methodname, *args)
      str_args = args.collect {|member|'"'+member+'"'}
      vim_cmd = "#{methodname}( #{str_args.join ','})"
      evaluate vim_cmd
    end	
  end

  class Commands
    def self.dot *args
      self.method_missing(".", args)
    end

    def self.method_missing(methodname, *args)
      vim_cmd = "#{methodname} #{args.join ' '}"
      command(vim_cmd)
    end
  end

  class Editor
    def open_file(partial_name)
      current_tab.open_file(partial_name)
    end

    def code
      current_tab.code
    end

    def current_tab
      Tab.new Buffer.current
    end

    def file
      current_tab.file
    end

    def create_tab filename
      File.open(filename, "w") do |file|
        file << "#created by hal9000 at #{Time.now}"
      end
      Commands.tabnew filename
      current_tab
    end

    def create_tab_with_confirm filename
      confirm = confirm_create? filename
      self.create filename if confirm
      return confirm 
    end

    private 
    def confirm_create? filename
      message = "create file #{filename}?"
      Functions.confirm(message, "yes\nno") == "1"
    end
  end

  class Tab
    def initialize buffer
      @buffer=buffer
    end

    def file
      @buffer.name
    end

    def open_file(filename)
      Commands.n "**/*#{filename}*"
    end

    def code
      result = ""
      for line in 1..@buffer.count
        result << @buffer[line].strip + "\n"
      end
      result
    end

    def format_all
      old_line = current_line
      Commands.normal('gg=G')
      goto_line old_line            
    end

    private

    def goto_line line_no
      Commands.dot line_no
    end

    def current_line
      Functions.line(".").to_i - 1            
    end
  end
end
